<template>
  <form>
    <label v-if="label"><span style="color: red;">*</span>{{label}}:</label>
    <slot></slot>
    <br />
    <span style="color: red;font-size: 12px;" v-show="errorMessage">{{errorMessage}}</span>
  </form>
</template>
<script>
  import Schema from "async-validator";
  export default {
    inject: ['form'],
    props: {
      label: String,
      prop: String,
    },
    data(){
      return {
        errorMessage: ''
      }
    },
    mounted(){
      this.$on('validate', this.validate);
    },
    methods: {
      validate() {
        // 获取校验规则
        const rules = this.form.rules[this.prop];
        // 获取数据模型
        const value = this.form.model[this.prop];
        // 校验对象
        const descriptor = {
          [this.prop]: rules
        }
        // 创建校验器
        const schema = new Schema(descriptor);
        // 执行校验
        schema.validate({ [this.prop]: value }, errors => {
          if (errors) {
            this.errorMessage = errors[0].message;
          } else {
            this.errorMessage = '';
          }
        })
      }
    }
  }
</script>